// Copyright 2024 awol2005ex
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Utility functions for kinit

use std::error::Error;

/// Parse principal string into username and realm
pub fn parse_principal(principal: &str) -> Result<(&str, &str), Box<dyn Error>> {
    let parts: Vec<&str> = principal.split('@').collect();
    if parts.len() != 2 {
        return Err("Principal must be in format username@REALM".into());
    }
    Ok((parts[0], parts[1]))
}

/// Extract username from principal
pub fn get_username(principal: &str) -> Result<&str, Box<dyn Error>> {
    parse_principal(principal).map(|(username, _)| username)
}

/// Extract realm from principal  
pub fn get_realm(principal: &str) -> Result<&str, Box<dyn Error>> {
    parse_principal(principal).map(|(_, realm)| realm)
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_parse_principal() {
        let principal = "hdfs@TEST.COM";
        let (username, realm) = parse_principal(principal).unwrap();
        assert_eq!(username, "hdfs");
        assert_eq!(realm, "TEST.COM");
        
        let principal2 = "admin/user@EXAMPLE.COM";
        let (username2, realm2) = parse_principal(principal2).unwrap();
        assert_eq!(username2, "admin/user");
        assert_eq!(realm2, "EXAMPLE.COM");
    }
    
    #[test]
    fn test_get_username() {
        let principal = "hdfs@TEST.COM";
        let username = get_username(principal).unwrap();
        assert_eq!(username, "hdfs");
    }
    
    #[test]
    fn test_get_realm() {
        let principal = "hdfs@TEST.COM";
        let realm = get_realm(principal).unwrap();
        assert_eq!(realm, "TEST.COM");
    }
}